package com.example.controller;

import com.example.pojo.Personal;
import com.example.service.PersonalService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by IntelliJ IDEA2021.3
 *
 * @Author: Tenghw
 * @Date: 2022/03/21  16:37
 * @Description:
 */
@Slf4j
@Controller
@SuppressWarnings("all")
public class ProviderHystrixController1 {
    @Autowired
    PersonalService personalService;

    @GetMapping(path = "/getAll")
    @ResponseBody
    public List<Personal> getAllPersonal() {
        log.info("=======进入controller层getAllPersonal()============");
        List<Personal> personals = personalService.getServiceAll();
        return personals;
    }




    @HystrixCommand(fallbackMethod = "errorCallBack",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="2000"),
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")})
    @GetMapping(path = "/getOne/{id}")
    @ResponseBody
    @SneakyThrows
    public Personal getOne(@PathVariable("id") int id) {
        log.info("=======进入controller层getOne()============");
        Personal personal = personalService.getServiceOne(id);
        TimeUnit.MILLISECONDS.sleep(3000);
        if (ObjectUtils.isEmpty(personal)) {
            throw new RuntimeException("请求的用户id,在数据库中不存在...");
        }
        return personal;
    }
    //不仅是超时，假设服务内的方法出现了异常，也同样会触发兜底的解决方法
    //兜底的方法处理，作为服务熔断的fallback
    public Personal errorCallBack(@PathVariable("id") int id) {
        log.info("==========进入controller层的errorCallBack()=============");
        Personal personal = new Personal();
        personal.setId(8888);
        personal.setName(null);
        personal.setCamp(null);
        personal.setRemarks("no this database in MySQL"+" : ——服务熔断，请求超时或其他异常...------" + id);
        return personal;
    }

}
